import { createPageWithStore } from '../../../../../../store/helpers/page_creator.js';
import { resourceStore } from '../../../../../../store/modules/resource/index.js';
import dayjs from 'dayjs';

createPageWithStore({
  /**
   * 页面的初始数据
   */
  data: {
    resourceId: '',
    resourceName: '',
    resourceType: null,
    resourceTypeName: '',
    
    versionList: [],
    isLoading: false,
    
    // 比较模态框
    showComparisonModal: false,
    compareVersionId: '',
    selectedVersionId: '',
    selectedVersion: '',
    versionSelectList: [],
    
    // 比较结果
    showComparisonResult: false,
    comparisonData: null,
    comparisonOldVersion: '',
    comparisonNewVersion: '',
    
    // 筛选条件
    showFilterModal: false,
    filterStatus: '',
    filterTime: '',
    sortField: 'createTime',
    sortOrder: 'desc',
    
    // 分页
    page: 1,
    size: 20,
    hasMore: true
  },
  
  // 使用Store
  useStore: {
    resourceStore
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 获取资源ID和名称
    const { resourceId, resourceName, resourceType } = options;
    
    if (!resourceId) {
      wx.showToast({ title: '资源ID不能为空', icon: 'none' });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
      return;
    }
    
    // 设置资源信息
    this.setData({
      resourceId,
      resourceName: resourceName || '资源版本列表',
      resourceType: resourceType ? parseInt(resourceType) : null
    });
    
    // 如果有资源类型，设置类型名称
    if (this.data.resourceType !== null) {
      const typeName = resourceStore.getResourceTypeName(this.data.resourceType);
      this.setData({ resourceTypeName: typeName });
    }
    
    // 加载版本列表
    this._loadVersionList(true);
  },
  
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    
  },
  
  /**
   * 下拉刷新
   */
  onPullDownRefresh() {
    this._loadVersionList(true);
    
    setTimeout(() => {
      wx.stopPullDownRefresh();
    }, 800);
  },
  
  /**
   * 上拉加载更多
   */
  onReachBottom() {
    if (this.data.hasMore && !this.data.isLoading) {
      this._loadVersionList(false);
    }
  },
  
  /**
   * 加载版本列表
   * @param {Boolean} refresh 是否刷新（true则重置分页）
   */
  async _loadVersionList(refresh = false) {
    if (this.data.isLoading) return;
    
    try {
      // 如果是刷新，重置分页数据
      if (refresh) {
        this.setData({
          page: 1,
          hasMore: true,
          versionList: []
        });
      }
      
      this.setData({ isLoading: true });
      
      // 构建筛选条件
      const filter = {};
      
      // 版本状态筛选
      if (this.data.filterStatus) {
        filter.status = parseInt(this.data.filterStatus);
      }
      
      // 时间筛选
      if (this.data.filterTime) {
        const days = parseInt(this.data.filterTime);
        const startTime = dayjs().subtract(days, 'day').unix();
        filter.startTime = startTime;
      }
      
      // 调用Store获取版本列表
      const result = await resourceStore.fetchVersionList(this.data.resourceId, {
        page: this.data.page,
        size: this.data.size,
        filter,
        sort: {
          field: this.data.sortField,
          order: this.data.sortOrder
        }
      });
      
      // 更新数据
      this.setData({
        versionList: refresh ? result : [...this.data.versionList, ...result],
        isLoading: false,
        page: this.data.page + 1,
        hasMore: result.length === this.data.size
      });
    } catch (error) {
      console.error('加载版本列表失败', error);
      wx.showToast({ title: '加载失败，请重试', icon: 'none' });
      this.setData({ isLoading: false });
    }
  },
  
  /**
   * 新增版本
   */
  onAddVersion() {
    wx.navigateTo({
      url: `/projects/plm/pages/resource/version/add/resource_version_add?resourceId=${this.data.resourceId}&resourceName=${this.data.resourceName}&resourceType=${this.data.resourceType || 0}`
    });
  },
  
  /**
   * 刷新列表
   */
  onRefresh() {
    this._loadVersionList(true);
  },
  
  /**
   * 点击筛选按钮
   */
  onFilter() {
    this.setData({ showFilterModal: true });
  },
  
  /**
   * 点击版本卡片
   */
  onVersionTap(e) {
    const { id } = e.detail;
    wx.navigateTo({
      url: `/projects/plm/pages/resource/version/detail/resource_version_detail?versionId=${id}`
    });
  },
  
  /**
   * 点击查看版本
   */
  onVersionViewTap(e) {
    const { id } = e.detail;
    wx.navigateTo({
      url: `/projects/plm/pages/resource/version/detail/resource_version_detail?versionId=${id}`
    });
  },
  
  /**
   * 点击比较版本
   */
  onVersionCompareTap(e) {
    const { id, version } = e.detail;
    
    // 设置要比较的版本
    this.setData({
      showComparisonModal: true,
      compareVersionId: id,
      selectedVersionId: '',
      selectedVersion: version,
      versionSelectList: []
    });
    
    // 加载可比较的版本列表
    this._loadCompareVersionList(id);
  },
  
  /**
   * 加载可比较的版本列表
   */
  async _loadCompareVersionList(excludeId) {
    try {
      // 使用已有的版本列表，过滤掉当前选中的版本
      const compareList = this.data.versionList
        .filter(v => v._id !== excludeId)
        .map(v => ({
          id: v._id,
          version: v.VERSION || v.version,
          createTime: v.CREATE_TIME ? dayjs.unix(v.CREATE_TIME).format('YYYY-MM-DD') : ''
        }));
      
      this.setData({ versionSelectList: compareList });
    } catch (error) {
      console.error('加载比较版本列表失败', error);
      wx.showToast({ title: '加载失败，请重试', icon: 'none' });
    }
  },
  
  /**
   * 选择要比较的版本
   */
  onSelectCompareVersion(e) {
    const { id, version } = e.currentTarget.dataset;
    this.setData({
      selectedVersionId: id,
      selectedVersion: version
    });
  },
  
  /**
   * 关闭比较模态框
   */
  onCloseComparisonModal() {
    this.setData({ showComparisonModal: false });
  },
  
  /**
   * 确认比较版本
   */
  async onConfirmCompare() {
    if (!this.data.selectedVersionId) return;
    
    try {
      // 获取两个版本的详细信息
      const versionAId = this.data.compareVersionId;
      const versionBId = this.data.selectedVersionId;
      
      wx.showLoading({ title: '比较中...' });
      
      // 调用Store进行版本比较
      const result = await resourceStore.compareVersions(
        this.data.resourceId,
        versionAId,
        versionBId
      );
      
      wx.hideLoading();
      
      if (!result) {
        wx.showToast({ title: '比较失败，请重试', icon: 'none' });
        return;
      }
      
      // 获取版本号
      const versionA = this.data.versionList.find(v => v._id === versionAId);
      const versionB = this.data.versionList.find(v => v._id === versionBId);
      
      const oldVersion = versionA.VERSION || versionA.version;
      const newVersion = versionB.VERSION || versionB.version;
      
      // 关闭比较模态框，显示比较结果
      this.setData({
        showComparisonModal: false,
        showComparisonResult: true,
        comparisonData: result,
        comparisonOldVersion: oldVersion,
        comparisonNewVersion: newVersion
      });
    } catch (error) {
      wx.hideLoading();
      console.error('版本比较失败', error);
      wx.showToast({ title: '比较失败，请重试', icon: 'none' });
    }
  },
  
  /**
   * 关闭比较结果页
   */
  onCloseComparisonResult() {
    this.setData({ showComparisonResult: false });
  },
  
  /**
   * 点击设置为当前版本
   */
  async onSetCurrentTap(e) {
    const { id } = e.detail;
    
    wx.showModal({
      title: '设置当前版本',
      content: '确定要将此版本设为当前版本吗？',
      success: async (res) => {
        if (res.confirm) {
          try {
            wx.showLoading({ title: '设置中...' });
            
            // 调用Store设置当前版本
            await resourceStore.setCurrentVersion(this.data.resourceId, id);
            
            wx.hideLoading();
            wx.showToast({ title: '设置成功' });
            
            // 刷新列表
            this._loadVersionList(true);
          } catch (error) {
            wx.hideLoading();
            console.error('设置当前版本失败', error);
            wx.showToast({ title: '设置失败，请重试', icon: 'none' });
          }
        }
      }
    });
  },
  
  /**
   * 下载文件
   */
  onDownloadFile(e) {
    const { url, version, isOld } = e.detail;
    
    if (!url) {
      wx.showToast({ title: '文件链接不存在', icon: 'none' });
      return;
    }
    
    console.log(`下载${isOld ? '旧' : '新'}版本文件: ${version}, ${url}`);
  },
  
  /**
   * 选择筛选状态
   */
  onSelectFilterStatus(e) {
    const { status } = e.currentTarget.dataset;
    this.setData({ filterStatus: status });
  },
  
  /**
   * 选择筛选时间
   */
  onSelectFilterTime(e) {
    const { time } = e.currentTarget.dataset;
    this.setData({ filterTime: time });
  },
  
  /**
   * 选择排序方式
   */
  onSelectSort(e) {
    const { field, order } = e.currentTarget.dataset;
    this.setData({ 
      sortField: field,
      sortOrder: order
    });
  },
  
  /**
   * 重置筛选条件
   */
  onResetFilter() {
    this.setData({
      filterStatus: '',
      filterTime: '',
      sortField: 'createTime',
      sortOrder: 'desc'
    });
  },
  
  /**
   * 应用筛选条件
   */
  onApplyFilter() {
    this.setData({ showFilterModal: false });
    this._loadVersionList(true);
  },
  
  /**
   * 关闭筛选模态框
   */
  onCloseFilterModal() {
    this.setData({ showFilterModal: false });
  },
  
  /**
   * 阻止模态框的触摸穿透
   */
  preventTouchMove() {
    return false;
  },
  
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    // 清理Store中的数据
    resourceStore.clearVersionList();
    resourceStore.clearVersionComparison();
  }
}); 